const Router = require('koa-router')
const compose = require('koa-compose')
const Context = require('./context')

let routes = []

exports.Controller = class Controller {
	constructor(app = {}) {
		Object.assign(this, app)
		this.created()
	}
	created() {
		let router = new Router({
			prefix: this.prefix || ''
		})

		router[this.method](
			this.Url,
			...[
				...(this.perform || []),
				async (ctx, next) => {
					// let context = new Context(ctx, this)
					await this.handle.call(ctx)
					return next()
				}
			]
		)
		routes.push(router.routes())

		this.logger.info('create router', [this.method, this.prefix + this.Url])
	}
	static routes() {
		return compose(routes)
	}
}

/**
 * path of request, match buy koa-router
 */
exports.url = path => traget => {
	traget.prototype.Url = path
}

/**
 * method for request
 * @param {String} 支持 POST GET PUT DEL ALL
 */
exports.method = method => {
	return traget => {
		traget.prototype.method = (method + '').toLowerCase()
	}
}

exports.perform = fn => {
	if (typeof fn !== 'function') return
	return traget => {
		let perform = traget.prototype.perform
		traget.prototype.perform = perform ? [...perform, fn] : [fn]
	}
}

/**
 * prefix of router
 */
exports.prefix = prefix => traget => {
	traget.prototype.prefix = prefix
}
